<?php

if (!function_exists('handleCover')) {
    function handleCover(string $name)
    {
        if (empty($name)) {
            $data[0] = '';
            $data[1] = (object) [];
        } else {
            $data[0] = env('IMG_DOMAIN') . $name;
            $data[1] = ['name' => $name, 'url' => env('IMG_DOMAIN') . $name];
        }

        return $data;
    }
}

if (!function_exists('handleImages')) {
    function handleImages(string $images)
    {
        $images = json_decode($images, true);
        if (empty($images)) {
            $data[0] = [];
            $data[1] = [];
        } else {
            $data[0] = $images;
            $data[1] = [];
            foreach ($images as $key => $value) {
                $data[1][$key]['url'] = env('IMG_DOMAIN') . $images[$key];
            }
        }

        return $data;
    }

}

if (!function_exists('objectToArray')) {
    /**
     * objectToArray 对象转数组
     * @param $object
     * @return mixed
     */
    function objectToArray($object)
    {
        return json_decode(json_encode($object), true);
    }
}

if (!function_exists('arrayToObject')) {
    /**
     * arrayToObject 数组转对象
     * @param $array
     * @return mixed
     */

    function arrayToObject($array)
    {
        if (is_array($array)) {
            $obj = new stdClass();
            foreach ($array as $key => $val) {
                $obj->$key = $val;
            }
        } else {
            $obj = $array;
        }
        return $obj;

    }
}

if (!function_exists('getTree')) {
    /**
     * getTree 无限极分类树
     * @param $arr
     * @return array
     */
    function getTree($arr)
    {
        $refer = array();
        $tree = array();
        foreach ($arr as $k => $v) {
            $refer[$v['id']] = &$arr[$k]; //创建主键的数组引用
        }
        foreach ($arr as $k => $v) {
            $pid = $v['pid']; //获取当前分类的父级id
            if ($pid == 0) {
                $tree[] = &$arr[$k]; //顶级栏目
            } else {
                if (isset($refer[$pid])) {
                    $refer[$pid]['children'][] = &$arr[$k]; //如果存在父级栏目，则添加进父级栏目的子栏目数组中
                }
            }
        }
        return $tree;
    }
}

if (!function_exists('generateTree')) {
    function generateTree($data)
    {
        $items = array();
        foreach ($data as $v) {
            $items[$v['id']] = $v;
        }
        $tree = array();
        foreach ($items as $k => $item) {
            if (isset($items[$item['pid']])) {
                $items[$item['pid']]['children'][] = &$items[$k];
            } else {
                $tree[] = &$items[$k];
            }
        }
        return $tree;
    }
}

if (!function_exists('getFileSize')) {
    /**
     * getFileSize 字节转换kb
     * @param $num
     * @return string
     */
    function getFileSize($num)
    {
        $p = 0;
        $format = 'bytes';
        if ($num > 0 && $num < 1024) {
            $p = 0;
            return number_format($num) . ' ' . $format;
        }
        if ($num >= 1024 && $num < pow(1024, 2)) {
            $p = 1;
            $format = 'KB';
        }
        if ($num >= pow(1024, 2) && $num < pow(1024, 3)) {
            $p = 2;
            $format = 'MB';
        }
        if ($num >= pow(1024, 3) && $num < pow(1024, 4)) {
            $p = 3;
            $format = 'GB';
        }
        if ($num >= pow(1024, 4) && $num < pow(1024, 5)) {
            $p = 3;
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 3) . ' ' . $format;
    }
}

if (!function_exists('getRemoteFileSize')) {
    // 获取远程图片大小
    function getRemoteFileSize($url, $user = '', $pw = '')
    {
        ob_start();
        $ch = curl_init($url); // make sure we get the header
        curl_setopt($ch, CURLOPT_HEADER, 1); // make it a http HEAD request
        curl_setopt($ch, CURLOPT_NOBODY, 1); // if auth is needed, do it here
        if (!empty($user) && !empty($pw)) {
            $headers = array('Authorization: Basic ' . base64_encode($user . ':' . $pw));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        $okay = curl_exec($ch);
        curl_close($ch); // get the output buffer
        $head = ob_get_contents(); // clean the output buffer and return to previous // buffer settings
        ob_end_clean(); // gets you the numeric value from the Content-Length // field in the http header
        $regex = '/Content-Length:\s([0-9].+?)\s/';
        $count = preg_match($regex, $head, $matches); // if there was a Content-Length field, its value // will now be in $matches[1]
        if (isset($matches[1])) {
            $size = $matches[1];
        } else {
            $size = 'unknown';
        }
        $last_mb = round($size / (1024 * 1024), 3);
        $last_kb = round($size / 1024, 3);
        // return $last_kb . 'KB / ' . $last_mb . ' MB';
        return $last_kb . 'KB';
    }
}

// 二维数组的差集
if (!function_exists('getDyaicArrayDiff')) {
    function getDyaicArrayDiff($arr1, $arr2)
    {
        try {
            return array_values(array_filter($arr1, function ($v) use ($arr2) {
                    return !in_array($v, $arr2);
                })
            );
        } catch (\Exception $exception) {
            return $arr1;
        }

    }
}

if (!function_exists('curlRequest')) {
    /**
     * @Description: curl请求
     * @Author: Yang
     * @param $url
     * @param null $data
     * @param string $method
     * @param array $header
     * @param bool $https
     * @param int $timeout
     * @return mixed
     */
    function curlRequest($url, $data = null, $method = 'get', $header = array("content-type: application/json"), $https = true, $timeout = 5)
    {
        $method = strtoupper($method);
        $ch = curl_init(); //初始化
        curl_setopt($ch, CURLOPT_URL, $url); //访问的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只获取页面内容，但不输出
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https请求 不验证证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
        }
        if ($method != "GET") {
            if ($method == 'POST') {
                curl_setopt($ch, CURLOPT_POST, true); //请求方式为post请求
            }
            if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //请求数据
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        //curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
        $result = curl_exec($ch); //执行请求
        curl_close($ch); //关闭curl，释放资源
        return $result;
    }
}
